package com.jxud.service.impl;

import com.jxud.Pojo.Users;
import com.jxud.mapper.OrderMapper;
import com.jxud.mapper.UserMapper;
import com.jxud.service.UsersService;
import com.jxud.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Transactional
@Service
public class UsersServiceImpi implements UsersService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private OrderServiceImpi  orderServiceImpi;

    @Override
    public Users login(Users users) {
        return userMapper.getByUsernameAndPassword(users);
    }

    @Override
    public String registerUser(Users users) {
        String hashedPassword = passwordEncoder.encode(users.getPassword());
        users.setPassword(hashedPassword);
        try{
            userMapper.save(users);
            return "用户"+users.getUsername()+"注册成功";
        }catch (Exception e){
            return "用户"+users.getUsername()+"注册失败：" + e.getMessage();
        }
    }

    /**
     * 获取客户信息
     * @return
     */
    @Override
    public List<Users> getUser(Users users, HttpServletRequest request) {
        String token = request.getHeader("token");
        Claims claims = JwtUtils.parseJwt(token);
        String wxName = (String) claims.get("wxName");
        if (wxName.equals("admin")){
            return userMapper.getUser(users);
        }
        return null;
    }
}
